package org.bear.graph.base;

public class NumIslands {
    private int res = 0;

    private char[][] grid;

    public int numIslands(char[][] grid) {
        if (grid==null || grid.length==0){
            return 0;
        }
        this.grid = grid;
        for(int i=0;i<grid.length;i++){
            for(int j=0;j<grid[0].length;j++){
                visitCurPos(i, j);
            }
        }
        return res;
    }

    private void visitCurPos(int i, int j){
        if (grid[i][j]=='1'){
            res++;
            dfsOccupy(i, j);
        }
    }

    private void dfsOccupy(int i, int j){
        if (grid[i][j]=='1'){
            grid[i][j] = '2';
        } else {
            return;
        }

        // 上
        if (i-1>=0){
            dfsOccupy(i-1, j);
        }
        // 下
        if (i+1<grid.length){
            dfsOccupy(i+1, j);
        }
        // 左
        if (j-1>=0){
            dfsOccupy(i, j-1);
        }
        // 右
        if (j+1<grid[0].length){
            dfsOccupy(i, j+1);
        }

    }



}
